package com.example.common.xss;


import com.example.common.utils.excel.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;

import java.util.*;

/**
 * @program: xss-demo
 * @description: 初始化敏感词库，将敏感词加入到HashMap中，构建DFA算法模型
 * @author: ChenZhiXiang
 * @create: 2019-07-22 14:40
 **/
@Slf4j
public class SensitiveWordInit {

    /** 字符编码 */
    private static final String CHARACTER_ENCODING = "UTF-8";

    /** 敏感词存放Map */
    public HashMap sensitiveWordMap;

    public Map initKeyWord(String sensitiveFilePath) {
        try {
            // 读取敏感词库
            Set<String> keyWordSet = readSensitiveWordFile(sensitiveFilePath);
            addSensitiveWordToHashMap(keyWordSet);
        }catch (Exception e){
            log.info("出错了");
        }
        return sensitiveWordMap;
    }

    /**
     * 读取敏感词库中的内容，将内容添加到set集合中
     * @param sensitiveFilePath
     * @return
     * @throws Exception
     */
    private Set<String> readSensitiveWordFile(String sensitiveFilePath) throws Exception{
        Set<String> set = new HashSet<>();
        //读取文件
        Workbook workbook = ExcelUtil.readExcel(sensitiveFilePath);
        List<String[]> mgList = ExcelUtil.readFromWorkbook(workbook,new ArrayList<>());
        for(int i = 0 ;i<mgList.size();i++){
            set.add(mgList.get(i)[0]);
        }
        return set;
    }

    /**
     * 将敏感词集合加入到Map中
     * @param keyWordSet
     */
    private void addSensitiveWordToHashMap(Set<String> keyWordSet) {
        // 初始化敏感词容器，减少扩容操作
        sensitiveWordMap = new HashMap(keyWordSet.size());
        String key = null;
        Map nowMap = null;
        Map<String, String> newWorMap = null;
        //迭代keyWordSet
        Iterator<String> iterator = keyWordSet.iterator();
        while(iterator.hasNext()){
            //关键字
            key = iterator.next();
            nowMap = sensitiveWordMap;
            for(int i = 0 ; i < key.length() ; i++){
                //转换成char型
                char keyChar = key.charAt(i);
                //获取
                Object wordMap = nowMap.get(keyChar);

                if(wordMap != null){
                    //如果存在该key，直接赋值
                    nowMap = (Map) wordMap;
                }
                else{     //不存在则，则构建一个map，同时将isEnd设置为0，因为他不是最后一个
                    newWorMap = new HashMap<String,String>();
                    //不是最后一个
                    newWorMap.put("isEnd", "0");
                    nowMap.put(keyChar, newWorMap);
                    nowMap = newWorMap;
                }

                if(i == key.length() - 1){
                    //最后一个
                    nowMap.put("isEnd", "1");
                }
            }
        }
    }
}
